package com.nuanshui.heatedloan.controller.display.wechat;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.springContext.SpringPropertiesUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.SSOTokenUtil;
import com.nuanshui.framework.utils.model.Pair;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.extension.security.SecurityContextService;
import com.nuanshui.heatedloan.middleware.whatchat.util.WechatPPUtil;
import com.nuanshui.heatedloan.constant.EnvironmentType;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.service.services.SafeTokenUtil;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.facade.UserWeixinAccountService;
import com.nuanshui.heatedloan.userinfo.facade.wechat.WeChatService;
import com.nuanshui.heatedloan.userinfo.form.BoundUserForm;
import com.nuanshui.heatedloan.userinfo.form.UserForm;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.model.WechatUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import weixin.popular.bean.sns.SnsToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WeChatController extends BaseController {


    private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private SSOTokenUtil ssoTokenUtil;

    @Reference(url = GlobalParam.USER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private WeChatService weChatService;

    @Reference(url = GlobalParam.USER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserWeixinAccountService userWeixinAccountService;

    @Reference(url = GlobalParam.USER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserService userService;

    @Autowired
    private SecurityContextService securityContextService;

    @Autowired
    private SafeTokenUtil safeTokenUtil;

    /**
     * 获得js中wx对象签名
     *
     * @author Junyan2015
     * @date 2016年2月18日 上午10:58:13
     */
    @RequestMapping(value = "/getSignInfo",method = RequestMethod.POST)
    public String getSignatureInfo(String signUrl) {
        LogUtil.debug(logger, "------------------微信接口调试--------------------------");
        String environment = SpringPropertiesUtil.getPropertiestValue("base.conf.environment");
        if (EnvironmentType.ENVIRONMENTTYPE_DEV.equals(environment)) {
            LogUtil.debug(logger, "------------------测试环境不允许获取！--------------------------");
            return error("测试环境不允许获取微信签名");
        }

        Map<String, Object> map = weChatService.getSignatureInfo(signUrl);
        LogUtil.debug(logger, "------------------微信分享接口返回参数：" + JSON.toJSONString(map));
        return success(map);
    }


    /**
     * 微信登录
     *
     * @author Junyan2015
     * @date 2016年4月18日 上午11:03:13
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(String code, String redirectUrl) {
        User user = this.weChatService.login(code, redirectUrl);
        ssoTokenUtil.generateToken(user.getId(), getResponse());
        LogUtil.info(logger, redirectUrl);
        return "redirect:" + redirectUrl;
    }


    /**
     * 微信网页登录
     *
     * @author Junyan2015
     * @date 2016年4月18日 上午11:04:06
     */
    @RequestMapping(value = "wechatLogin",method = RequestMethod.POST)
    @ResponseBody
    public String wechatLogin(String code) {
        if (code == null)
            error("code值不能为空");
        logger.info("code:" + code);
        //WechatOpenId wechat = WechatUtil.getOpenid(code);
        SnsToken snsToken=WechatPPUtil.getSnsToken(code);
        if (snsToken == null || SysStringUtils.isEmpty(snsToken.getOpenid()))
            error("无法获取用户的openid");
        WechatUserInfo info = userWeixinAccountService.getWechatUserInfo(snsToken);
        info.setSafeToken(ssoTokenUtil.generateToken(info.getUserId(), getResponse()));
        info.setLoginType(WechatUserInfo.LOGINTYPE_WECHAT);

        return success(info);
    }


    /**
     * 微信页面 用手机号登录
     *
     * @param phone
     * @param pwd
     * @return
     * @author Sven
     */
    @RequestMapping(value = "/loginByPhone",method = RequestMethod.POST)
    @ResponseBody
    public String loginByPhoneInWechat(String phone, String pwd) {
        User u = userService.loginByPhone(phone, pwd);

        if(u!=null)
        {
            WechatUserInfo info = new WechatUserInfo();
            info.setUserId(u.getId());

            Pair<String,String> tokenPair=safeTokenUtil.generateToken(info.getUserId());
            info.setSafeToken(tokenPair.getKey());
            info.setLoginType(WechatUserInfo.LOGINTYPE_PHONE);

            securityContextService.setAuthenticationWithToken(u,tokenPair.getValue());

            return success(info);
        }
        return error("账号或密码错误");
    }

    /**
     * 微信中  忘记密码  并重置密码
     *
     * @param form
     * @param errors
     * @param req
     * @param resp
     * @return
     * @Author: Sven
     */
    @RequestMapping(value = "/forget-pwd-login",method = RequestMethod.POST)
    @ResponseBody
    public String loginDynamicPwdValidate(@Valid UserForm form, Errors errors, HttpServletRequest req, HttpServletResponse resp) {
        /*if (!veriFacade.verifyCode(form.getMobile(), form.getSmsCode(),
                SmsType.DYNAMIC_DYNAMICORREGI)) {
            throw new BizException(GlobalErrorCode.UNKNOWN, "验证码错误");
        }

        User newUser = userService.loadByLoginname(form.getMobile());
        if (newUser == null) throw new BizException
                (GlobalErrorCode.UNKNOWN, "该手机号未注册");
        Integer versionInt = 0;

        if (versionInt >= 120 && SysStringUtils.isEmpty(form.getPwd())) {
            throw new BizException(GlobalErrorCode.UNKNOWN, "密码不能为空");
        }
        if (!SysStringUtils.isEmpty(form.getPwd())) {
            newUser.setPassword(pwdEncoder.encode(form.getPwd()));
            userService.updateUserInfo(newUser, false);
        }
        WechatUserInfo info = new WechatUserInfo();
        info.setUserId(newUser.getId());
        info.setSafeToken(ssoTokenUtil.generateToken(info.getUserId(), getResponse()));
        info.setLoginType(WechatUserInfo.LOGINTYPE_PHONE);*/
        return success(/*info*/);
    }

    /**
     * 在微信中用手机号登陆的用户  绑定微信号
     *
     * @return
     * @Author: Sven
     */
    @RequestMapping(value = "/bindWechat",method = RequestMethod.POST)
    @ResponseBody
    public String bindWechatAccount(BoundUserForm boundUserForm) {
        weChatService.bindWechatAccount(boundUserForm);
        return success();
    }

    /**
     * 获取微信用户信息 通过code
     *
     * @param code
     * @return
     * @Author: Sven
     */
    @RequestMapping("/getWechatUserInfo")
    @ResponseBody
    public String getWechatUserByCode(String code) {
        //return WechatUtil.getWechatUserByCode(code);
        return  WechatPPUtil.getStrByCode(code);
    }

}
